import os
import shutil
import html2text
import tkinter as tk
from tkinter import filedialog
from bs4 import BeautifulSoup, Comment
import re
import threading

def convert_html_to_md(html_folder, md_folder):
    if not os.path.exists(md_folder):
        os.makedirs(md_folder)

    # 记录 HTML 文件总数
    html_file_count = sum(1 for filename in os.listdir(html_folder) if filename.endswith(".html"))
    # 记录已经处理的 HTML 文件数量
    processed_count = 0

    for filename in os.listdir(html_folder):
        if filename.endswith(".html"):
            try:
                # 更新正在执行的文件显示
                update_current_file_label(filename)
                html_path = os.path.join(html_folder, filename)
                with open(html_path, 'r', encoding='utf-8') as f:
                    html_content = f.read()

                # 使用 BeautifulSoup 解析 HTML
                soup = BeautifulSoup(html_content, 'html.parser')

                # 移除 aside 标签及其内容
                for aside in soup.find_all('aside'):
                    aside.decompose()

                # 找到第一个 h1 标签
                first_h1 = soup.find('h1')
                if first_h1:
                    # 从第一个 h1 标签开始获取剩余的 HTML 内容
                    markdown_content = ""
                    for element in first_h1.next_siblings:
                        markdown_content += str(element)

                    # 创建 HTML2Text 对象并转换剩余内容
                    h = html2text.HTML2Text()
                    converted_text = h.handle(markdown_content)

                    # 处理图片（在 src 属性值前面加一个.）
                    img_tags = soup.find_all('img')
                    for img in img_tags:
                        src = img.get('src')
                        if src:
                            # 添加.到 src 属性值前面
                            new_src = "." + src
                            converted_text = converted_text.replace(src, new_src)
                else:
                    # 如果没有找到 h1 标签，直接转换整个内容
                    h = html2text.HTML2Text()
                    converted_text = h.handle(str(soup))

                # 生成对应的 markdown 文件路径
                md_filename = os.path.splitext(filename)[0] + ".md"
                md_path = os.path.join(md_folder, md_filename)
                with open(md_path, 'w', encoding='utf-8') as f:
                    f.write(converted_text)

                # 更新已处理文件数量
                processed_count += 1
                # 更新进度
                update_progress(processed_count, html_file_count)
            except Exception as e:
                print(f"Error processing {filename}: {e}")

def update_current_file_label(filename):
    current_file_label.config(text=f"Currently processing: {filename}")
    root.update()

def update_progress(current_count, total_count):
    progress_percentage = (current_count / total_count) * 100
    progress_label.config(text=f"Progress: {current_count}/{total_count} ({progress_percentage:.2f}%)")
    root.update()

def select_folder():
    folder_selected = filedialog.askdirectory()
    html_folder_entry.delete(0, tk.END)
    html_folder_entry.insert(0, folder_selected)
    md_folder = os.path.join(folder_selected, "converted_md")
    start_conversion(html_folder_entry.get(), md_folder)

def start_conversion(html_folder, md_folder):
    # 启动一个新线程来执行转换操作，以避免阻塞 GUI
    threading.Thread(target=convert_html_to_md, args=(html_folder, md_folder)).start()

root = tk.Tk()
root.title("HTML to MD Converter")

# 布局调整以适应 16:9 大致比例
root.geometry("800x450")

# 选择文件夹输入框和按钮
html_folder_label = tk.Label(root, text="HTML Folder:")
html_folder_label.pack(pady=10)
html_folder_entry = tk.Entry(root, width=50)
html_folder_entry.pack(pady=5)
select_button = tk.Button(root, text="Select Folder", command=select_folder)
select_button.pack(pady=10)

# 正在处理的文件显示标签
current_file_label = tk.Label(root, text="")
current_file_label.pack(pady=10)

# 进度显示标签
progress_label = tk.Label(root, text="")
progress_label.pack(pady=10)

root.mainloop()